package edu.tgc.service.system;

import java.util.UUID;

import org.abyss.common.annotation.Log;
import org.abyss.common.service.CommonCrudService;
import org.springframework.stereotype.Service;

import edu.tgc.entity.system.SysDuty;

@Log(value = "职责")
@Service
public class SysDutyService extends CommonCrudService<SysDuty, UUID> {

    protected boolean isParentChanged(SysDuty model, SysDuty saveEntity) {
        if (model.getParent() == null || model.getParent().getId() == null) {
            if (saveEntity.getParent() != null) {
                return true;
            }
        } else {
            if (saveEntity.getParent() == null) {
                return true;
            } else if (!saveEntity.getParent().equals(model.getParent())) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void preCreate(SysDuty model, SysDuty saveEntity) {
        super.preCreate(model, saveEntity);
        if (model.getParent() != null && model.getParent().getId() != null) {
            SysDuty parent = this.baseRepository.findOne(model.getParent().getId());
            saveEntity.setCodePath(parent.getCodePath() + "_" + model.getCode());
        } else {
            saveEntity.setCodePath(model.getCode());
        }
    }

    @Override
    protected void preUpdate(SysDuty model, SysDuty saveEntity) {
        super.preUpdate(model, saveEntity);
        if (model.getParent() != null && model.getParent().getId() != null) {
            SysDuty parent = this.baseRepository.findOne(model.getParent().getId());
            saveEntity.setCodePath(parent.getCodePath() + "_" + model.getCode());
        } else {
            saveEntity.setCodePath(model.getCode());
        }
        if (!saveEntity.getCode().equals(model.getCode()) || isParentChanged(model, saveEntity)) {
            resetCodePath(saveEntity);
        }
    }

    protected void resetCodePath(SysDuty saveEntity) {
        for (SysDuty children : saveEntity.getChildrens()) {
            children.setCodePath(saveEntity.getCodePath() + "_" + children.getCode());
            resetCodePath(children);
        }
    }

}
